<?php
require_once("{$CfgPara->root}/class/user_operate.class.php");
require_once("{$CfgPara->root}/class/mysql.func.php");
require_once("{$CfgPara->root}/class/do_edit_img.func.php");
require_once("{$CfgPara->root}/class/make_img_name.class.php");

/**
 * 消息数据模型
 *
 * @version 1.0
 * @author Human
 */
class message_m
{
    /**
     * 消息类型 提醒
     */
    const MsgRemind = 101;
    /**
     * 消息类型 评论
     */
    const MsgComment = 102;
    /**
     * 消息类型 关注
     */
    const MsgFollow = 103;
    /**
     * 消息类型 私信列表
     */
    const MsgPrivate = 104;
    /**
     * 消息类型 未读消息数
     */
    const MsgNoReadCount = 121;
    /**
     * 消息类型 管理员的消息 对话
     */
    const MsgAdDialog = 201;
    /**
     * 消息类型 管理员的消息 反馈
     */
    const MsgAdFeedback = 202;
    /**
     * 消息类型 管理员的消息 举报
     */
    const MsgAdReport = 203;
    /**
     * 消息类型 反馈/举报内的对话内容列表
     */
    const MsgAdRepostDialogList = 204;
    /**
     * 消息类型 私信对话内容列表
     */
    const MsgPrivateDialogList = 205;

    /**
     * 消息类型 系统消息
     */
    const MsgSystem = 206;

    /**
     * 消息类型 系统消息的详细内容
     */
    const MsgSystemContent = 207;

    public function __construct($dbPara = NULL)
    {
        if ($dbPara != null) {
            db_connect($dbPara);
        }
    }

    /**
     * 删除未读消息计数 正确返回true 错误返回错误信息
     * @param int $type 消息类型 参考消息类型常量
     * @param int $user_id
     * @return bool|string
     */
    public function msg_count_clear($type, $user_id)
    {
        if (!is_numeric($user_id)) {
            return '清除未读消息时，用户信息错误';
        }
        if ($type == message_m::MsgRemind) {
            $fname = 'Remind';
        } elseif ($type == message_m::MsgComment) {
            $fname = 'Comment';
        } elseif ($type == message_m::MsgFollow) {
            $fname = 'Follow';
        } elseif ($type == message_m::MsgPrivate) {
            $fname = 'Dialog';
        } else {
            return '清除未读消息时 消息类型错误';
        }
        $row[$fname] = 0;
        $row['UserId'] = $user_id;
        $result = db_update('message_count', $row, 'UserId');
        return $result;
    }

    /**
     * 未读消息数自减 20170224 当前仅用于反馈与举报消息
     * @param int $type 消息类型 参考消息类型常量
     */
    public function msg_count_sub($type)
    {
        if ($type == message_m::MsgAdFeedback) {
            $fname = 'Feedback';
            $tname = 'message_report_count';
        } elseif ($type == message_m::MsgAdReport) {
            $fname = 'Report';
            $tname = 'message_report_count';
        } else {
            return '减去未读消息时 消息类型错误';
        }
        $sql_str = "UPDATE `{$tname}` SET `{$fname}` = `{$fname}` - 1";
        $result = db_query($sql_str);
        if ($result !== true) {
            return db_error();
        } else {
            return true;
        }
    }

    /**
     * 获取未读消息数量 成功返回对象 失败返回错误信息
     * @param int $user_id 用户Id
     * @return mixed
     */
    public function msg_noread_count($user_id)
    {
        if (!is_numeric($user_id)) {
            return '查询未读消息数量时，用户信息错误';
        }
        // 同时也查询最新系统消息的时间与用户最近查看系统消息的时间
        // 由上层判断是否需要通知用户有新的系统消息
        $sql_str = "SELECT `message_count`.`Remind`,
                           `message_count`.`Comment`,
                           `message_count`.`Follow`,
                           `message_count`.`Dialog`,
                           `message_system`.`LastMsgDt`,
                           `message_system_user_view`.`ViewDt`
                    FROM `message_count`,`message_system`,`message_system_user_view` 
                    WHERE `message_count`.`UserId` = {$user_id} AND 
                          `message_system`.`Id` = 1 AND 
                          `message_system_user_view`.`UserId` = {$user_id} 
                    LIMIT 1";
        $result = db_get_object2($sql_str);
        if (is_string($result)) return $result;
        if ($result === 0) return '未查询到当前用户消息数';

        return $result;
    }

    /**
     * 获取某项消息的总数量 成功返回数量 失败返回错误信息
     * @param int $type 消息类型 参考本类的常量
     * @param int $id 用户id或信息id
     */
    public function msg_count($type, $id)
    {
        if (!is_numeric($id) || !is_numeric($type)) {
            return '查询消息总数量时，用户信息错误';
        }
        if ($type == message_m::MsgPrivateDialogList ||
            $type == message_m::MsgAdRepostDialogList
        ) {
            //id为整个对话的id
            $sql_str = "SELECT `DialogCount` FROM message_dialog WHERE `Id` = {$id}";
        } elseif ($type == message_m::MsgAdFeedback) {
            $sql_str = "SELECT `AllFeedback` FROM `message_report_count` LIMIT 1";
        } elseif ($type == message_m::MsgAdReport) {
            $sql_str = "SELECT `AllReport` FROM `message_report_count` LIMIT 1";
        } elseif ($type == message_m::MsgAdDialog) {
            $sql_str = "SELECT (`AllFeedback` + `AllReport`) as AllCount FROM `message_report_count` LIMIT 1";
        } elseif ($type == message_m::MsgComment) {
            $sql_str = "SELECT `AllComment` FROM `message_count` WHERE `UserId` = {$id}";
        } elseif ($type == message_m::MsgFollow) {
            $sql_str = "SELECT `AllFollow` FROM `message_count` WHERE `UserId` = {$id}";
        } elseif ($type == message_m::MsgPrivate) {
            $sql_str = "SELECT `AllDialog` FROM `message_count` WHERE `UserId` = {$id}";
        } elseif ($type == message_m::MsgRemind) {
            $sql_str = "SELECT `AllRemind` FROM `message_count` WHERE `UserId` = {$id}";
        } elseif ($type == message_m::MsgSystem) {
            $sql_str = "SELECT `MsgCount` FROM message_system WHERE `Id` = 1";
        } elseif ($type == message_m::MsgSystemContent) {
            return 1;
        }
        $result = db_query($sql_str);
        if ($result !== false) {
            if ($count = $result->fetch_array()) {
                return (int)$count[0];
            } else {
                return '获取消息总数量错误';
            }
        } else {
            return db_error();
        }
    }

    /**
     * 获取某项消息列表 成功返回消息对象的数组 失败返回错误信息
     * @param int $type 消息类型 参考本类的常量
     * @param int $id 用户id或信息id
     * @param int $page 第几页 当前页索引
     * @param int $page_size 每页数量
     * @param int $user_id 20170313 添加 举报/反馈的对话列表需要用户id与信息id 因此此处为用户id
     */
    public function msg_list($type, $id, $page, $page_size, $user_id = 0)
    {
        if (!is_numeric($id) || !is_numeric($type) || !is_numeric($page) || !is_numeric($page_size)) {
            return '查询消息列表时，提交的信息错误';
        }
        $sql_str = $this->get_list_sql($type, $id, $page, $page_size, $user_id);
        if ($sql_str === false) {
            return '查询消息列表时，消息类型错误';
        }
        $result = db_query($sql_str);
        if ($result === false) return db_error();
        $fetch_result = db_fetch_list($result, $rows);
        return $rows;
    }

    /**
     * 获取列表的sql语句
     * @param int $type 消息类型 参考本类的常量
     * @param int $id 用户id或信息id
     * @param int $page 第几页 当前页索引
     * @param int $page_size 每页数量
     */
    function get_list_sql($type, $id, $page, $page_size)
    {
        $limit_offset = ($page - 1) * $page_size;
        if ($type == message_m::MsgRemind) {
            $sql_str =
                "SELECT `message_remind`.* , `works`.`Name` as WorkName , `topic`.`Name` as TopicName , 
                `topic_works`.`State`, `works`.`Author`
                FROM `message_remind`, `works`, `topic` , `topic_works`
                WHERE `message_remind`.`MsgIdFrom` = `works`.`Id` AND 
                      `message_remind`.`MsgIdTo` = `topic`.`Id` AND 
                      `topic_works`.`TopicId` = `topic`.`Id` AND 
                      `topic_works`.`WorkId` = `works`.`Id` AND
                      `message_remind`.`UserId` = {$id}
                ORDER BY `message_remind`.`MsgDt` DESC LIMIT {$limit_offset},{$page_size}";
        } elseif ($type == message_m::MsgComment) {
            $sql_str = $this->get_comment_sql('message_comment', $id, $page, $page_size);
        } elseif ($type == message_m::MsgFollow) {
            $sql_str =
                "SELECT `message_follow`.* , `users`.`Name` as FollowUserName 
                FROM `message_follow`, `users`
                WHERE `message_follow`.`MsgIdFrom` = `users`.`Id` AND 
                      `message_follow`.`UserId` = {$id} 
                ORDER BY `message_follow`.`Id` DESC LIMIT {$limit_offset},{$page_size}";
        } elseif ($type == message_m::MsgPrivate) {
            // 需要同时将私信、反馈/举报、系统消息的对话查询出来
            $sql_str = "SELECT `message_dialog`.`Id` as DialogId ,
                               `message_dialog_content`.`MsgText`,
                               `message_dialog_content`.`MsgDt`,
                               DATE_FORMAT(`message_dialog_content`.`MsgDt`, '%y.%m.%d') as MsgDate,
                               `users`.`Name` as SendUserName, 
                               `users`.`Avatar` as SendUserAvatar,
                               `message_dialog`.`Type`
                        FROM `message_dialog`
                        INNER JOIN `message_dialog_content` 
                        ON (`message_dialog`.`UserId1` = {$id} OR 
                            `message_dialog`.`UserId2` = {$id}) AND 
                           `message_dialog`.`LastDialogId` = `message_dialog_content`.`Id` AND 
                           (`message_dialog`.`Type` = 0 OR `message_dialog`.`DialogCount` > 1)
                        LEFT JOIN `users`
                        ON (`message_dialog`.`UserId1` = `users`.`Id` OR 
                            `message_dialog`.`UserId2` = `users`.`Id`) AND 
                           `users`.`Id` != {$id}
                        UNION ALL
                        SELECT `message_system_content`.`Id` as DialogId,
                               `message_system_content`.`MsgTittle` as `MsgText`,
                               `message_system_content`.`MsgDt`,
                               DATE_FORMAT(`message_system_content`.`MsgDt`, '%y.%m.%d') as MsgDate,
                               '' as SendUserName,
                               '' as SendUserAvatar,
                               '9' as `Type`
                        FROM `message_system_content`,`message_system`
                        WHERE `message_system`.`Id` = 1 AND 
                              `message_system_content`.`Id` = `message_system`.`LastMsgId`
                        ORDER BY `MsgDt` 
                        DESC LIMIT {$limit_offset},{$page_size}";
        } elseif ($type == message_m::MsgAdDialog) {
            $sql_str =
                "SELECT `message_dialog`.`Id` as DialogId ,
                        `message_dialog`.`HasNew`,
                        `tittle`.`MsgText` as MsgTittle, 
                        `content`.`MsgText`,
                        DATE_FORMAT(`content`.`MsgDt`, '%y.%m.%d') as MsgDt,
                        `users`.`Name` as ReportUserName,
                        `content`.`SendUserId`,
                        `message_dialog`.`Type`
                FROM `message_dialog`, `users`, 
                     `message_dialog_content` as `content`, `message_dialog_content` as `tittle`
                WHERE `message_dialog`.`UserId2` = `users`.`Id` AND 
                      `message_dialog`.`UserId1` = 0 AND
                      `message_dialog`.`LastDialogId` = `content`.`Id` AND 
                      `message_dialog`.`FirstDialogId` = `tittle`.`Id` AND
                      `message_dialog`.`Type` != 0
                ORDER BY `content`.`MsgDt` DESC LIMIT {$limit_offset},{$page_size}";
        } elseif ($type == message_m::MsgAdFeedback ||
            $type == message_m::MsgAdReport
        ) {
            $reportType = (int)$type - 201;
            $sql_str =
                "SELECT `message_dialog`.`Id` as DialogId,
                        `message_dialog`.`HasNew`, 
                        `c1`.`MsgText`,
                        DATE_FORMAT(`c2`.`MsgDt`, '%y.%m.%d') as `MsgDt`,
                        `users`.`Name` as SendUserName,
                        `message_dialog`.`Type`
                FROM `message_dialog`, `users`, 
                     `message_dialog_content` as `c1`,
                     `message_dialog_content` as `c2`
                WHERE `message_dialog`.`UserId2` = `users`.`Id` AND 
                      `message_dialog`.`UserId1` = 0 AND
                      `message_dialog`.`FirstDialogId` = `c1`.`Id` AND
                      `message_dialog`.`LastDialogId` = `c2`.`Id` AND
                      `message_dialog`.`Type` = {$reportType}
                ORDER BY `c2`.`MsgDt` DESC LIMIT {$limit_offset},{$page_size}";
        } elseif ($type == message_m::MsgAdRepostDialogList) {
            // 按时间正序排序 将对话内容除了第一个全部获取
            $sql_str = "SELECT `message_dialog_content`.`MsgText`, 
                               `message_dialog_content`.`MsgDt`, 
                               `message_dialog_content`.`MsgPic`,
                               `message_dialog_content`.`SendUserId`,
                               `message_dialog`.`Type`
                        FROM `message_dialog_content`,`message_dialog`
                        WHERE `message_dialog_content`.`DialogId` = {$id} AND
                              `message_dialog`.`Id` = `message_dialog_content`.`DialogId` AND
                              `message_dialog_content`.`Id` != `message_dialog`.`FirstDialogId`
                        ORDER BY `MsgDt` LIMIT {$limit_offset},{$page_size}";
        } elseif ($type == message_m::MsgPrivateDialogList) {
            //按时间倒序排列
            $sql_str = "SELECT `t`.*, 
                               `users`.`Name` as SendUserName,
                               `users`.`Avatar` as SendUserAvatar  
                        FROM
                        (SELECT `message_dialog_content`.`SendUserId`,
                               `message_dialog_content`.`MsgText`, 
                               `message_dialog_content`.`MsgDt`, 
                               `message_dialog_content`.`MsgPic`
                        FROM `message_dialog_content`
                        WHERE `message_dialog_content`.`DialogId` = {$id}) as t
                        LEFT JOIN `users` 
                        ON `users`.`Id` = `t`.`SendUserId`
                        ORDER BY `MsgDt` DESC LIMIT {$limit_offset},{$page_size}";

        } elseif ($type == message_m::MsgSystem) {
            $sql_str = "SELECT `Id`,`MsgTittle`,`MsgText`,
                               DATE_FORMAT(`MsgDt`, '%y.%m.%d') as MsgDt
                        FROM `message_system_content` 
                        ORDER BY `message_system_content`.`MsgDt` 
                        DESC LIMIT {$limit_offset},{$page_size}";
        } else {
            $sql_str = false;
        }
        return $sql_str;
    }

    /**
     * 获取评论消息的Sql语句 错误将返回false
     */
    function get_comment_sql($table_name, $user_id, $page, $page_size)
    {
        $limit_offset = ($page - 1) * $page_size;
        $sql_str = "SELECT * FROM {$table_name} 
                    WHERE `UserId` = {$user_id} 
                    ORDER BY `Id` DESC LIMIT {$limit_offset},{$page_size}";
        $result = db_query($sql_str);
        if ($result !== false) {
            $fetch_result = db_fetch_list($result, $rows);
            $sql_str = '';
            foreach ($rows as $msg) {
                if ($msg->Type == 1 || $msg->Type == 3 || $msg->Type == 5) {
                    $comment_table = 'works_comment';
                    $show_table = 'works';
                    $fname = 'WorkId';
                    $ftextname = 'Name';
                } else {
                    $comment_table = 'show_comment';
                    $show_table = 'shoe_show';
                    $fname = 'ShowId';
                    $ftextname = 'Introd';
                }
                //获取消息时间、消息类型、评论者的用户名、评论者的头像、作品(鞋主秀)的Id
                $sql_str .= "SELECT '{$msg->MsgDt}' as MsgDt, '{$msg->Type}' as CommentType, 
                            `users`.`Name` as CommentUserName, `users`.`Avatar` as CommentUserAvatar, 
                            `{$show_table}`.`Id` as ShowId, `{$show_table}`.`{$ftextname}` as ShowName, `{$show_table}`.`Picture` as ShowPic,
                            `{$comment_table}`.`Id` as CommentId, `{$comment_table}`.`Text` as CommentText, `{$comment_table}`.`ReplyId` as CommentReplyId 
                            FROM `{$show_table}`,`users`, `{$comment_table}`
                            WHERE `{$show_table}`.`Id` = `{$comment_table}`.`{$fname}` AND 
                            `{$comment_table}`.`Id` = {$msg->MsgIdFrom} AND `users`.`Id` = `{$comment_table}`.`UserId` UNION ALL ";
            }
            $sql_str = substr($sql_str, 0, strlen($sql_str) - 10); //查询语句删除掉最后的'UNION ALL '
            return $sql_str;
        } else {
            return false;
        }
    }

    /**
     * 获取反馈/举报的内容 即反馈/举报对话的第一个内容 成功返回内容对象 失败返回错误信息
     * @param int $dialog_id 对话id
     */
    function get_msg_report($dialog_id)
    {
        if (!is_numeric($dialog_id)) return '查询反馈/举报内容时，提交的信息错误';
        $sql_str = "SELECT `message_dialog_content`.`MsgText`, 
                           `message_dialog_content`.`MsgDt`, 
                           `message_dialog_content`.`MsgPic`,
                           `message_dialog_content`.`SendUserId`,
                           `users`.`Name` as SendUserName,
                           `message_dialog`.`Type`,
                           `message_dialog`.`HasNew`
                    FROM `message_dialog_content`,`users`,`message_dialog`
                    WHERE `message_dialog_content`.`Id` = `message_dialog`.`FirstDialogId` AND
                          `message_dialog_content`.`SendUserId` = `users`.`Id` AND
                          `message_dialog`.`Id` = {$dialog_id}";
        $result = db_query($sql_str);
        if ($result === false) {
            return db_error();
        }
        if ($report = $result->fetch_object()) {
            // 如果当前用户为管理员登陆 且对话标记为有新的内容 则重新标记为没有新内容
            if ($report->HasNew == 1 &&
                isset ($_SESSION['user_level']) && $_SESSION['user_level'] >= 90 &&
                isset ($_SESSION['user_admin']) && $_SESSION['user_admin'] == 1
            ) {
                $row = array();
                $row['Id'] = $dialog_id;
                $row['HasNew'] = 0;
                $result = db_update('message_dialog', $row);
                if (is_string($result)) return $result;
            }
            return $report;
        } else {
            return '未找到此对话信息';
        }
    }

    /**
     * 获取系统消息的详细内容  成功返回内容对象 失败返回错误信息
     * @param int $id 内容id
     */
    function get_msg_system($id)
    {
        if (!isset ($_SESSION['user_id']) && !is_numeric($_SESSION['user_id']))
            return '查询系统消息内容时，请先登陆';
        if (!is_numeric($id)) return '查询系统消息内容时，提交的信息错误';
        // 更新当前用户的系统消息查看时间
        // 时间字段为自动更新时间戳类型
        $row = array();
        $row['UserId'] = $_SESSION['user_id'];
        $row['ViewCount'] = '`ViewCount` + 1';
        $result = db_update('message_system_user_view', $row, 'UserId');
        if (is_string($result)) return $result;
        $sql_str = "SELECT * FROM `message_system_content` WHERE `Id` = $id";
        $result = db_query($sql_str);
        if ($result === false) {
            return db_error();
        }
        if ($row = $result->fetch_object()) {
            return $row;
        } else {
            return '未找到此对话信息';
        }
    }

    /**
     * 私信发送 如果正确 返回1 错误返回错误信息
     * @param mixed $to_user_name 发送目标的用户名
     * @param mixed $from_user_id 发送人的用户Id
     * @param mixed $send 发送内容
     * @param string $img_names 发送的图片名 已保存在临时文件夹
     * @return mixed
     */
    function msg_private_send($to_user_name, $from_user_id, $send, $img_names)
    {
        if (!is_numeric($from_user_id)) {
            return '私信发送时，提交的用户信息错误';
        }
        $from_user_id = (int)$from_user_id;
        $to_user_name_text = urldecode($to_user_name);
        $to_user_name_text = db_escape($to_user_name_text);
        if ($to_user_name_text === false) {
            return '私信发送时，输入的用户名不合法';
        }
        $result = db_get_object('users', 'Name', $to_user_name_text);
        if (is_string($result)) {
            return $result;
        } elseif ($result === 0) {
            return '私信发送时，找不到发送对象';
        } else {
            $to_user_id = $result->Id;
        }
        //用户Id小的始终为UserId1
        if ($to_user_id < $from_user_id) {
            $user_id1 = $to_user_id;
            $user_id2 = $from_user_id;
        } else {
            $user_id1 = $from_user_id;
            $user_id2 = $to_user_id;
        }
        if ($to_user_id == $from_user_id) {
            return '私信发送时，不能自己发送给自己';
        }
        db_begin();
        //查找与发送到的用户的对话
        $sql_str = "SELECT `Id` FROM `message_dialog` 
                    WHERE `UserId1` = {$user_id1} AND `UserId2` = {$user_id2}";
        $result = db_query($sql_str);
        if ($result !== false) {
            if ($result->num_rows > 0) {
                $row = $result->fetch_array();
                $dialog_id = $row[0];
                if (!is_numeric($dialog_id)) {
                    return '对话组获取错误';
                }
            } else {
                //之前没有对话 插入
                $new_dialog = true;
                $row = array();
                $row['UserId1'] = $user_id1;
                $row['UserId2'] = $user_id2;
                $row['DialogCount'] = 1;
                $dialog_id = db_save('message_dialog', $row);
                if (!is_numeric($dialog_id)) {
                    db_rollback();
                    return $dialog_id;
                }
            }
        } else {
            return $result;
        }
        global $CfgPara;
        $imgs = do_edit_img(2, $img_names, "{$CfgPara->root}/message_pic/", '', 'MsgPic');
        if ($imgs === false) return '处理上传图片时发生错误';
        $send_text = urldecode($send);
        $send_text = db_escape($send_text);
        if ($send_text === false) {
            return '私信发送时，输入的内容不合法';
        }
        //插入对话内容 
        $row = array();
        $row['DialogId'] = $dialog_id;
        $row['MsgText'] = "'{$send_text}'";
        $row['MsgPic'] = "'{$imgs}'";
        $row['SendUserId'] = $from_user_id;
        $row['RecvUserId'] = $to_user_id;
        $content_id = db_save('message_dialog_content', $row);
        if (!is_numeric($content_id)) {
            db_rollback();
            return $content_id;
        }
        //更新对话的内容id
        $row = array();
        $row['Id'] = $dialog_id;
        if (isset ($new_dialog)) {
            $row['FirstDialogId'] = $content_id;
        } else {
            $row['DialogCount'] = '`DialogCount` + 1'; //自增1
        }
        $row['LastDialogId'] = $content_id;
        $row['HasNew'] = 1;
        $result = db_update('message_dialog', $row);
        if (is_string($result)) {
            db_rollback();
            return $result;
        }
        //更新接收方消息数
        $row = array();
        if (isset ($new_dialog)) {
            $row['AllDialog'] = '`AllDialog` + 1';
            //更新发送方消息数
            $row['UserId'] = $from_user_id;
            $result = db_update('message_count', $row, 'UserId');
            if (is_string($result)) {
                db_rollback();
                return $result;
            }
        }
        $row['Dialog'] = '`Dialog` + 1';
        $row['UserId'] = $to_user_id;
        $result = db_update('message_count', $row, 'UserId');
        if (is_string($result)) {
            db_rollback();
            return $result;
        }
        db_commit();
        return 1;
    }

    /**
     * 系统消息发送 如果正确 返回1 错误返回错误信
     * @param string $tittle 消息标题
     * @param string $send_text 发送文本内容
     * @param string $img_names 发送的图片名 已保存在临时文件夹
     * @return mixed
     */
    function msg_system_send($tittle, $send_text, $img_names)
    {
        if (!isset ($_SESSION['user_id'])) {
            return '无操作权限 请登陆';
        }
        if (isset ($_SESSION['user_level']) && $_SESSION['user_level'] >= 90 &&
            isset ($_SESSION['user_admin']) && $_SESSION['user_admin'] == 1
        ) {
            db_begin();
            global $CfgPara;
            $imgs = do_edit_img(
                2, $img_names,
                "{$CfgPara->root}/message_pic/", 'message_dialog_content', 'MsgPic');
            if ($imgs === false) return '处理上传图片时发生错误';

            $tittle = urldecode($tittle);
            $tittle = db_escape($tittle);
            if ($tittle === false) return '发送的标题内容不合法';
            $tLen = mb_strlen($tittle, 'utf8');
            if ($tLen < 2) return '消息标题字符数必须大于等于3';
            if ($tLen > 30) return '消息标题字符数不能大于30';
            $send_text = urldecode($send_text);
            $send_text = db_escape($send_text);
            if ($send_text === false) return '发送的文本内容不合法';
            $tLen = mb_strlen($tittle, 'utf8');
            if ($tLen < 5) return '消息内容字符数必须大于等于5';
            if ($tLen > 135) return '消息标题字符数不能大于135';
            // 插入消息内容
            $row = array();
            $row['MsgText'] = "'{$send_text}'";
            $row['MsgPic'] = "'{$imgs}'";
            $row['SendUserId'] = $_SESSION['user_id'];
            $row['MsgTittle'] = "'{$tittle}'";
            $result = db_save('message_system_content', $row);
            if (!is_numeric($result)) {
                db_rollback();
                return $result;
            }
            $content_id = $result;
            // 更新最新消息信息
            $row = array();
            $row['Id'] = 1;
            $row['MsgCount'] = '`MsgCount` + 1';
            $row['LastMsgId'] = $content_id;
            $result = db_update('message_system', $row);
            if (is_string($result)) {
                db_rollback();
                return $result;
            }
            // 更新所有用户的系统消息未读数
            // 不更新，查询时，如果用户的查看系统消息时间，比最新系统消息时间要早
            // 则在界面上自动增加一个私信未读数
            db_commit();
            return 1;
        } else {
            return '无权限发送系统消息 请以管理员身份登陆';
        }
    }

    /**
     * 反馈/举报的对话回复 如果正确 返回1 错误返回错误信息
     * @param int $dialog_id 所在对话的Id
     * @param string $send_text 发送的文本内容
     * @param int $img_names
     * @param int $report_id 回复所属的反馈/举报的id
     * @return mixed
     */
    function msg_report_reply($dialog_id, $send_text, $img_names)
    {
        if (!is_numeric($dialog_id)) {
            return '回复发送时，提交的信息错误';
        }
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return '回复发送时，请先登陆';
        }
        //获取对话信息
        $result = db_get_object('message_dialog', 'Id', $dialog_id);
        if (is_string($result)) return $result;
        if ($result === 0) return '回复发送时，未找到对话信息';
        if ($result->UserId1 != 0 || ($result->Type != 1 && $result->Type != 2)) {
            return '回复发送时，未检测到合法对话信息';
        }
        if ($_SESSION['user_level'] >= 90 && $_SESSION['user_admin'] == 1) {
            //当前用户为管理员
            $send_user_id = 0;
            $recv_user_id = $result->UserId2;
        } else {
            if ($result->UserId2 == $_SESSION['user_id']) {
                $send_user_id = $_SESSION['user_id'];
                $recv_user_id = 0;
            } else {
                return '回复发送时，未检测您的对话信息';
            }
        }

        if ($send_user_id == $recv_user_id) {
            return '回复发送时，不能自己发送给自己';
        }

        $dialog_id = $result->Id;
        global $CfgPara;
        $imgs = do_edit_img(
            2, $img_names, "{$CfgPara->root}/message_pic/", 'message_dialog_content', 'MsgPic');
        if ($imgs === false) return '处理上传图片时发生错误';
        $send_text = urldecode($send_text);
        $send_text = db_escape($send_text);
        if ($send_text === false) {
            return '回复发送时，输入的内容不合法';
        }
        db_begin();
        //插入对话内容
        $row = array();
        $row['DialogId'] = $dialog_id;
        $row['MsgText'] = "'{$send_text}'";
        $row['MsgPic'] = "'{$imgs}'";
        $row['SendUserId'] = $send_user_id;
        $row['RecvUserId'] = $recv_user_id;
        $result = db_save('message_dialog_content', $row);
        if (!is_numeric($result)) {
            db_rollback();
            return $result;
        }
        $content_id = $result;
        // 更新对话的最新信息
        $row = array();
        $row['Id'] = $dialog_id;
        $row['LastDialogId'] = $content_id;
        $row['HasNew'] = 1;
        $row['DialogCount'] = '`DialogCount` + 1';
        $result = db_update('message_dialog', $row);
        if (is_string($result)) {
            db_rollback();
            return $result;
        }
        // 如果接收方为普通用户 给用户增加未读私信数
        if ($recv_user_id != 0) {
            $row = array();
            $row['UserId'] = $recv_user_id;
            $row['Dialog'] = '`Dialog` + 1';
            $result = db_update('message_count', $row, 'UserId');
            if (is_string($result)) {
                db_rollback();
                return $result;
            }
        }
        db_commit();
        return 1;
    }

    /**
     * 进行消息反馈或举报 正确返回1 失败返回错误信息
     * @param int $type 类型 202反馈 203举报
     * @param int $img_names 已提交的图片名字符串
     * @param string $text 提交的文字内容
     */
    public function msg_report($type, $img_names, $text)
    {
        if ($type != message_m::MsgAdFeedback &&
            $type != message_m::MsgAdReport
        ) {
            return '提交的消息不是反馈或举报';
        }
        if (!isset ($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return '当前未登陆，请先登陆';
        }
        //每次的反馈/举报 都作为新的对话 插入
        $row = array();
        $row['UserId1'] = 0;
        $row['UserId2'] = $_SESSION['user_id'];
        $row['DialogCount'] = 1;
        $row['Type'] = (int)$type - 201;
        $row['HasNew'] = 1;
        $dialog_id = db_save('message_dialog', $row);
        if (!is_numeric($dialog_id)) {
            db_rollback();
            return $dialog_id;
        }
        global $CfgPara;
        $imgs = do_edit_img(
            2, $img_names,
            "{$CfgPara->root}/message_pic/", 'message_dialog_content', 'MsgPic');
        if ($imgs === false) return '处理上传图片时发生错误';
        $text = db_escape(urldecode($text));
        $tLen = mb_strlen($text, 'utf8');
        if ($tLen > 135) {
            return '提交的内容大于135个字符';
        } elseif ($tLen < 5) {
            return '提交的内容小于5个字符';
        }
        //插入新的反馈或举报的对话内容
        $row = array();
        $row['DialogId'] = $dialog_id;
        $row['MsgText'] = "'{$text}'";
        $row['MsgPic'] = "'{$imgs}'";
        $row['SendUserId'] = $_SESSION['user_id'];
        $row['RecvUserId'] = 0;
        $content_id = db_save('message_dialog_content', $row);
        if (!is_numeric($content_id)) {
            db_rollback();
            return $content_id;
        }
        //更新对话的内容id
        $row = array();
        $row['Id'] = $dialog_id;
        $row['FirstDialogId'] = $content_id;
        $row['LastDialogId'] = $content_id;
        $row['HasNew'] = 1;
        $result = db_update('message_dialog', $row);
        if (is_string($result)) {
            db_rollback();
            return $result;
        }
        //更新反馈/举报数
        if ($type == message_m::MsgAdFeedback) {
            $fname = 'Feedback'; //反馈
        } else {
            $fname = 'Report'; //举报
        }
        $row = array();
        $row['Id'] = 1;
        $row[$fname] = "`{$fname}` + 1";
        $row['All' . $fname] = "`All{$fname}` + 1";
        $result = db_update('message_report_count', $row);
        if (is_string($result)) {
            db_rollback();
            return $result;
        }
        // 更新反馈/举报者的对话数
        $row = array();
        $row['UserId'] = $_SESSION['user_id'];
        $row['AllDialog'] = '`AllDialog` + 1';
        $result = db_update('message_count', $row, 'UserId');
        if (is_string($result)) {
            db_rollback();
            return $result;
        }
        return 1;
    }

    /**
     * 根据对话id 获取对话另外一方的用户名
     * @param int $type 类型 1反馈 2举报
     * @param int $img_names 已提交的图片名字符串
     * @param string $text 提交的文字内容
     */
    public function get_dialog_username($dialog_id)
    {
        if (!is_numeric($dialog_id) || !isset ($_SESSION['user_id'])) return '无法获取用户名';
        $result = db_get_object('message_dialog', 'Id', $dialog_id);
        if (is_string($result)) return '无法获取用户名';
        if ($result->UserId1 == $_SESSION['user_id']) {
            $user_id = $result->UserId2;
        } elseif ($result->UserId2 == $_SESSION['user_id']) {
            $user_id = $result->UserId1;
        }
        if (!isset ($user_id)) return '无法获取用户名';
        $value = $user_id;
        $result = db_get_data('users', 'Name', 'Id', $value);
        if ($result === 0) return '无法获取用户名';
        if ($result !== 1) return $result;
        return $value;
    }

    /**
     * 获取消息编辑器预装的文本
     * @param int $type 类型 1作品 2鞋主秀
     * @param string $txt 预装内容 作品为作品名 鞋主秀为作品名|鞋主秀内容
     */
    public function get_edit_pre($type, $txt)
    {
        if (!is_numeric($type)) {
            return '';
        }
        $txt = urldecode($txt);
        if ($type == 1) //作品
        {
            return "作品《{$txt}》";
        } elseif ($type == 2) //鞋主秀
        {
            //作品名称与鞋主秀内容用|号分隔开
            $s = explode('|', $txt, 2);
            if (!empty($s) && count($s) == 2) {
                return "作品《{$s[0]}》的鞋主秀内容:{$s[1]}";
            }
        } else {
            return '';
        }
    }

    /**
     * 判断是否有新的管理员消息 如果有返回1 失败或没有返回-1
     */
    public function has_new_admin_msg()
    {
        $sql_str = "SELECT `Id` FROM `message_dialog` 
                    WHERE `HasNew` = 1 AND 
                          (`Type` = 1 OR `Type` = 2)";
        $result = db_get_object2($sql_str);
        if (!is_string($result) && $result !== 0) {
            return 1;
        } else {
            return -1;
        }
    }

    /**
     * 判断是否有新的反馈/举报消息
     * 返回数组['Feedback']/['Report'] 如果有为1 没有为0 如果失败返回错误信息
     */
    public function has_new_report()
    {
        $sql_str = "SELECT `Type` FROM `message_dialog`
                    WHERE `HasNew` = 1 AND `Type` = 1 LIMIT 1
                    UNION ALL
                    SELECT `Type` FROM `message_dialog` 
                    WHERE `HasNew` = 1 AND `Type` = 2 LIMIT 1";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        $row = array();
        $row['Feedback'] = 0;
        $row['Report'] = 0;
        while ($dialog = $result->fetch_object()) {
            if ($dialog->Type == 1) {
                $row['Feedback'] = 1;
            } elseif ($dialog->Type == 2) {
                $row['Report'] = 1;
            }
        }
        return $row;
    }
}
